package com.zhima.controller.plain;

import cn.hutool.core.io.IoUtil;
import com.zhima.service.OjQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/question")
public class QuestionDownLoadController {
    @Autowired
    private OjQuestionService ojQuestionService;

    @GetMapping("/download/test-case/{questionId}")
    public HttpServletResponse downloadTestCase(@PathVariable("questionId") Long questionId, HttpServletResponse response) throws IOException {
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s", URLEncoder.encode("testCases.zip", StandardCharsets.UTF_8)));
        response.setContentType(String.format("%s charset=utf-8", MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE));
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setStatus(HttpServletResponse.SC_OK);
        IoUtil.copy(new ByteArrayInputStream(ojQuestionService.downloadTestCase(questionId)), response.getOutputStream());
        return response;
    }
}
